package 
{
	import adobe.utils.MMEndCommand;
	import adobe.utils.MMExecute;
	import fl.containers.BaseScrollPane;
	import fl.containers.ScrollPane;
	import fl.containers.UILoader;
	import fl.controls.Button;
	import fl.controls.TextInput;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	import zdc.Util;
	
	/**
	 * 
	 * @author simple slime
	 */
	public class Main extends MovieClip 
	{
		private var _t:TextInput;
		private var _b:Button;
		private var _img:ScrollPane;
		private var _ref:FileReference;
		private var _loader:Loader;
		private var _bmp:Bitmap;
		private var _bd:BitmapData;
		
		public function Main() 
		{
			_t = this.txt;
			_b = this.btn;
			_img = this.img;
			_b.addEventListener(MouseEvent.CLICK, loadFile);
			
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadOk);
			_img.addChild(_loader);  
			//trace(getRGBA(16777215));
		}
		
		private function onLoadOk(e:Event):void 
		{
			_bmp = _loader.content as Bitmap;
			_bd = _bmp.bitmapData;
			var count:int = _bd.getPixels(_bd.rect).length
			var ps:Array = [];
			for (var i:int = 0; i < _bd.width; i++) {
				var p2:Array = [];
				for (var j:int = 0; j < _bd.height; j++) {
					p2.push(toJsRGBA(_bd.getPixel32(i, j)));
				}
				ps.push('[' + p2.join(",") + ']');
			}
			var arr:String = '[' + ps.join(",") + ']';
			//trace(arr);
			callJs('WritePng', 'writePng(' + arr + ' );');
		}
		
		private function loadFile(e:Event = null):void {
			_ref = new FileReference();
			_ref.addEventListener(Event.COMPLETE, onComplete);
			_ref.addEventListener(Event.SELECT, onSelect);
			//_ref.addEventListener(DataEvent.DATA, onComplete);
			_ref.browse([new FileFilter("Images", "*.jpg;*.gif;*.png")]); 
		}
		
		private function onSelect(e:Event):void 
		{
			trace("selected!");
			_ref.load(); 
		}
		
		private function onComplete(e:Event):void 
		{
			_loader.loadBytes(_ref.data);
		}
		
		private function callJs(jsFile:String, script:String):void {
			MMExecute('fl.runScript(fl.configURI + "jsfl/' + jsFile + '.jsfl")');
			MMExecute(script);
		}
		
		private function getRGBA(color:uint):Array {
			var a:uint = color >> 24 & 0xff;
			var r:uint = color >> 16 & 0xff;
			var g:uint = color >> 8 & 0xff;
			var b:uint = color & 0xff;	 
			return [r.toString(16), g.toString(16), b.toString(16), a.toString(16)];
		}
		
		private function toJsRGBA(color:uint):String {
			return "'#" + (getRGBA(color).join("") + "'");
		}
	}

}